using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;

public class ResourceManager : MonoBehaviour
{

    public static ResourceManager Instance { get; private set;}

    public event EventHandler OnResourceAmountChanged;

    private Dictionary<ResourceType, int> resourceAmountDictionary; // 资源类型与数量的字典

    private void Awake()
    {
        Instance = this;

        resourceAmountDictionary = new Dictionary<ResourceType, int>(); // 初始化资源字典

        // 加载资源类型列表
        ResourceTypeList resourceTypeList = Resources.Load<ResourceTypeList>("ScriptableObject/资源类型/资源类型列表");

        // 遍历资源类型列表，将每个资源类型添加到资源字典并初始化数量为0
        foreach (ResourceType resourceType in resourceTypeList.list)
        {
            resourceAmountDictionary[resourceType] = 0;
        }
    }

    public void AddResource(ResourceType resourceType, int amount){
        resourceAmountDictionary[resourceType] += amount; // 增加资源数量

        OnResourceAmountChanged?.Invoke(this, EventArgs.Empty);
    }

    // 获取资源数量
    public int GetResourceAmount(ResourceType resourceType){
        return resourceAmountDictionary[resourceType];
    }

    public bool CanAfford(ResourceAmount[]resourceAmountArray){
        // 遍历所有资源类型和数量
        foreach (ResourceAmount resourceAmount in resourceAmountArray){
            if (GetResourceAmount(resourceAmount.resourceType) < resourceAmount.amount){
                // 支付不起该资源，返回 false
                return false; 
            }
        }
        // 所有资源的数量都足够支付，返回 true
        return true;
    }

    public void SpendResources(ResourceAmount[] resourceAmountArray){
        // 遍历所有资源类型和数量
        foreach (ResourceAmount resourceAmount in resourceAmountArray){
            // 减少对应资源类型的数量
            resourceAmountDictionary[resourceAmount.resourceType] -= resourceAmount.amount;
        }
    }
}
